//
//  SettingViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/13.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "SettingViewController.h"
#import "SettingTableViewCell.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "SettingGesturePwdViewController.h"
#import <Masonry.h>
#import "LoginViewController.h"
#import "NavigateViewController.h"

#import "PCCircleViewConst.h"
#import "AppTools.h"
//验证手势
#import "ResetGestureViewController.h"
//修改密码
#import "ChangePwdViewController.h"


@interface SettingViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *loginStyleSettingArray;
@property(nonatomic,strong)NSMutableArray *changePwdArray;

@property(nonatomic,strong)NSMutableArray *loginStyleSettingImvArray;
@property(nonatomic,strong)NSMutableArray *changePwdImvArray;

@property(nonatomic,strong)UIButton *logoutBtn;

@end

@implementation SettingViewController

-(NSMutableArray *)loginStyleSettingArray
{
    if (_loginStyleSettingArray == nil) {
        _loginStyleSettingArray = [NSMutableArray array];
    }
    return _loginStyleSettingArray;
}

-(NSMutableArray *)changePwdArray
{
    if (_changePwdArray == nil) {
        _changePwdArray = [NSMutableArray array];
    }
    return _changePwdArray;
}

-(NSMutableArray *)loginStyleSettingImvArray
{
    if (_loginStyleSettingImvArray == nil) {
        _loginStyleSettingImvArray = [NSMutableArray array];
    }
    return _loginStyleSettingImvArray;
}

-(NSMutableArray *)changePwdImvArray
{
    if (_changePwdImvArray == nil) {
        _changePwdImvArray = [NSMutableArray array];
    }
    return _changePwdImvArray;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    if (![AppTools isLogin]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    self.view.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:244 / 255.0 blue:246 / 255.0 alpha:1];
    //创建tableView
    [self createTableView];
    //退出
    [self logout];
    
}

-(void)logout
{
    self.logoutBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.logoutBtn setTitle:@"退出登录" forState:(UIControlStateNormal)];
    self.logoutBtn.backgroundColor = [UIColor colorWithRed:91 / 255.0 green:113 / 255.0 blue:255 / 255.0 alpha:1];
    self.logoutBtn.layer.cornerRadius = 22;
    [self.view addSubview:self.logoutBtn];
    [self.logoutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.bottom.equalTo(self.view).offset(-50);
        make.height.mas_equalTo(44);
    }];
    
    [self.logoutBtn addTarget:self action:@selector(logoutBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
}
-(void)logoutBtnAction
{
    
    //记录登录状态
    [AppTools saveLoginStatus:NO];
    //银行卡、信用卡、POS数、推荐人数置0
    [AppTools shareInstance].userInfo.creditCardNum = @"0";
    [AppTools shareInstance].userInfo.cdrdsNum = @"0";
    [AppTools shareInstance].userInfo.recomendNum = @"0";
    [AppTools shareInstance].userInfo.posCardsNum = @"0";
    
    
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    NavigateViewController *nav = [[NavigateViewController alloc] initWithRootViewController:loginVC];
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)createTableView
{
    self.loginStyleSettingArray = @[@"开启指纹解锁",@"设置手势解锁"].mutableCopy;
    self.changePwdArray = @[@"修改登录密码"].mutableCopy;
    
    self.loginStyleSettingImvArray= @[@"set_icon_touch",@"set_icon_shoushi"].mutableCopy;
    self.changePwdImvArray = @[@"set_icon_message"].mutableCopy;
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerClass:[SettingTableViewCell class] forCellReuseIdentifier:@"cell"];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.loginStyleSettingArray.count;
    }else
    {
        return self.changePwdArray.count;
    }
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //指纹使用switch
    if (indexPath.section == 0 && indexPath.row == 0) {
        cell.arrowImv.hidden = YES;
        cell.mySwitch.hidden = NO;
        //switch事件
        [cell.mySwitch addTarget:self action:@selector(mySwitchAction:) forControlEvents:(UIControlEventValueChanged)];
    }else
    {
        cell.arrowImv.hidden = NO;
        cell.mySwitch.hidden = YES;
    }
    
    
    if (indexPath.section == 0) {
        cell.titleLab.text = self.loginStyleSettingArray[indexPath.row];
        cell.imv.image = [UIImage imageNamed:self.loginStyleSettingImvArray[indexPath.row]];
        //最后一个cell不显示分割线
        if (indexPath.row == self.loginStyleSettingArray.count - 1) {
            cell.lineView.hidden = YES;
        }
    }else
    {
        cell.imv.image = [UIImage imageNamed:self.changePwdImvArray[indexPath.row]];
        cell.titleLab.text = self.changePwdArray[indexPath.row];
        //最后一个cell不显示分割线
        if (indexPath.row == self.changePwdArray.count - 1) {
            cell.lineView.hidden = YES;
        }
    }
    
    //获取到switch是否打开渲染UI
    if (indexPath.section == 0 && indexPath.row == 0) {
        if ([AppTools isOpenedFingerprint]) {
            cell.mySwitch.on = YES;
        }else
        {
            cell.mySwitch.on = NO;
        }
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了tableView");
    if (indexPath.section == 0 && indexPath.row == 1) {
        NSLog(@"手势登录设置");
        SettingGesturePwdViewController *settingVC = [[SettingGesturePwdViewController alloc] init];
        [self.navigationController pushViewController:settingVC animated:YES];
    }
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        NSLog(@"修改密码");
        ChangePwdViewController *changeVC = [[ChangePwdViewController alloc] init];
        [self.navigationController pushViewController:changeVC animated:YES];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.0f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.01)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(void)mySwitchAction:(UISwitch *)sender
{
    
    if (sender.on) {
        NSLog(@"打开指纹不验证");
        
#warning 后端可以登录了在测试
        //判断设备支持指纹的话
        if (![self checkPhoneSupportFinger]) {
            [self showFailedResultTips:@"该设备暂不支持指纹" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            SettingTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.mySwitch.on = NO;
            return;
        }
        
        
        
        //开启touchId先检测是否开启了手势
        if ([AppTools isIsOpenedGesture]) {
            //验证手势,成功之后开启指纹
            ResetGestureViewController *resetVC = [[ResetGestureViewController alloc] init];
            [resetVC setType:(openTouchId)];
            [self.navigationController pushViewController:resetVC animated:YES];
            
        }else
        {
            //直接打开指纹
            [PCCircleViewConst saveFingerprint:@"1" Key:fingerprintStatueKey];
            
        }
    }else
    {
        NSLog(@"关闭指纹");
        [self TouchId];
        [PCCircleViewConst saveFingerprint:@"0" Key:fingerprintStatueKey];
        
    }
}

-(BOOL)checkPhoneSupportFinger
{
    NSString *version = [UIDevice currentDevice].systemVersion;
    if ([version integerValue] < 8.0) {
        return NO;
    }
    
    LAContext *lacontext = [[LAContext alloc]init];
    // 判断设备是否支持指纹识别
    BOOL isSupport = [lacontext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:NULL];
    if(!isSupport)
    {
        NSLog(@"不支持！");
        return NO;
    }else
    {
        return YES;
    }
    
}


-(void)TouchId
{
    NSString *version = [UIDevice currentDevice].systemVersion;
    if ([version integerValue] < 8.0) {
        NSLog(@"系统版本不支持TouchID");
        //开通指纹失败
        [PCCircleViewConst saveFingerprint:@"0" Key:fingerprintStatueKey];
        return;
    }
    LAContext *context = [[LAContext alloc] init];
    context.localizedFallbackTitle = @"";
    NSError *error = nil;
    
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"通过Home键验证已有手机指纹" reply:^(BOOL success, NSError * _Nullable error) {
            
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"TouchID 验证成功");
                    [PCCircleViewConst saveFingerprint:@"0" Key:fingerprintStatueKey];
                });
            }else if(error){
                //关闭指纹失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [PCCircleViewConst saveFingerprint:@"1" Key:fingerprintStatueKey];
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                    SettingTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                    cell.mySwitch.on = YES;
                    
                });
                
                
                
                    switch (error.code) {
                    case LAErrorAuthenticationFailed:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 验证失败");
                            //当第三次的时候系统会提示验证失败
                            [self showFailedResultTips:@"验证失败" animated:YES forSeconds:1.5];
                        });
                        break;
                    }
                    case LAErrorUserCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 被用户手动取消");
                        });
                    }
                        break;
                    case LAErrorUserFallback:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"用户不使用TouchID,选择手动输入密码");
                        });
                    }
                        break;
                    case LAErrorSystemCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 被系统取消 (如遇到来电,锁屏,按了Home键等)");
                        });
                    }
                        break;
                    case LAErrorPasscodeNotSet:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无法启动,因为用户没有设置密码");
                        });
                    }
                        break;
                    case LAErrorTouchIDNotEnrolled:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无法启动,因为用户没有设置TouchID");
                        });
                    }
                        break;
                    case LAErrorTouchIDNotAvailable:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无效");
                        });
                    }
                        break;
                    case LAErrorTouchIDLockout:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self openSystemPassword];
                            NSLog(@"TouchID 被锁定(连续多次验证TouchID失败,系统需要用户手动输入密码)");
                        });
                    }
                        break;
                    case LAErrorAppCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"当前软件被挂起并取消了授权 (如App进入了后台等)");
                        });
                    }
                        break;
                    case LAErrorInvalidContext:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"当前软件被挂起并取消了授权 (LAContext对象无效)");
                        });
                    }
                        break;
                    default:
                        break;
                }
            }
        }];
        
    }else{
        NSLog(@"当前设备不支持TouchID");
        //关闭指纹失败
        [PCCircleViewConst saveFingerprint:@"1" Key:fingerprintStatueKey];
        //打开系统密码
        [self openSystemPassword];
        dispatch_async(dispatch_get_main_queue(), ^{
 
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            SettingTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.mySwitch.on = YES;
        });
    }
}

-(void)openSystemPassword
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        LAContext *myContext=[[LAContext alloc] init];
        NSError *error=nil;
        
        if([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error])
        {
            [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"通过Home键验证已有手机指纹" reply:^(BOOL success, NSError * _Nullable error) {
                
            }];
            
        }
    });
}



@end
